import { initBackEndControlRoutes } from '/@/router/backEnd';
import {GetUserMaxPermissionV2} from '../api/login/login.js'
import { ElMessage } from 'element-plus';  
import router from '../router'
export const selectRoles = (data) => {
  return new Promise(async (resolve) => {
    let token = localStorage.getItem("token");
    let proj_oid
    let oldAuthCode = localStorage.getItem("authCode");
    localStorage.getItem("selectedProject") ? proj_oid = JSON.parse(localStorage.getItem("selectedProject"))
    .proj_oid :  localStorage.getItem("project")&&JSON.parse(localStorage.getItem("project")).projectInfo? proj_oid = JSON.parse(localStorage.getItem("project")).projectInfo.proj_oid
     : proj_oid = localStorage.getItem("refrushProId")
    let resUser = await GetUserMaxPermissionV2({
      proj_oid: data?.proj_oid,
      user_token: token,
    });
  
    if(resUser.roles.length==0){
      ElMessage({
        message: '您没有权限',
        type: 'error',
        duration: 5 * 1000
      })
      localStorage.clear()
      sessionStorage.clear()
      window.location.reload()
      return 
    }

    localStorage.setItem("userMessage", JSON.stringify(resUser));
    localStorage.setItem("authCode", resUser.maxPermission);

    if (parseInt(oldAuthCode)!==resUser.maxPermission&&(Object.keys(resUser).length > 0)) {
      
        const isNoPower = await initBackEndControlRoutes();
        
        sessionStorage.setItem('path',router.currentRoute.value.fullPath)
        router.push({name:'noPower'})
        resolve(isNoPower)
    }else{
      resolve()
    }
  });
};
